﻿CREATE PROCEDURE [dbo].[ew_sp_install_pre]
    @uid_easyweb_id UNIQUEIDENTIFIER, 
    @vc_name        VARCHAR(1024), 
    @vc_version     VARCHAR(1024), 
    @b_upgrade      BIT OUTPUT
AS
    SET @b_upgrade = 0

    DECLARE @vc_current_name    VARCHAR(1024),
            @vc_current_version VARCHAR(1024),
            @i_current_major    INT,
            @i_current_minor    INT,
            @i_current_build    INT,
            @i_current_revision INT,
            @i_new_major        INT,
            @i_new_minor        INT,
            @i_new_build        INT,
            @i_new_revision     INT

    -- New installation

    IF NOT EXISTS (SELECT 1 FROM ew_tbl_easyweb WHERE ew_uid_easyweb_id = @uid_easyweb_id)
    BEGIN
        GOTO UPGRADE_END
    END

    -- Check upgrade

    SELECT
        @vc_current_name    = ew_vc_name,
        @vc_current_version = ew_vc_version
    FROM ew_tbl_easyweb
    WHERE ew_uid_easyweb_id = @uid_easyweb_id

    EXEC ew_sp_parse_version
        @vc_version = @vc_current_version,
        @i_major    = @i_current_major    OUTPUT,
        @i_minor    = @i_current_minor    OUTPUT,
        @i_build    = @i_current_build    OUTPUT,
        @i_revision = @i_current_revision OUTPUT

    EXEC ew_sp_parse_version
        @vc_version = @vc_version,
        @i_major    = @i_new_major    OUTPUT,
        @i_minor    = @i_new_minor    OUTPUT,
        @i_build    = @i_new_build    OUTPUT,
        @i_revision = @i_new_revision OUTPUT

    -- The current version is greater than or equal the upgrade version

    IF @i_current_major > @i_new_major
        GOTO NON_UPGRADE_END
    ELSE IF @i_current_major < @i_new_major
        GOTO UPGRADE_END
    ELSE IF @i_current_minor >= @i_new_minor     -- only database change should upgrade the minor version
        GOTO NON_UPGRADE_END
    ELSE IF @i_current_minor < @i_new_minor
        GOTO UPGRADE_END

UPGRADE_END:

    SET @b_upgrade = 1

NON_UPGRADE_END:
RETURN 0
